<template>
    <div class="white-box">
        <title-more :title="`${type == 1 ? '新建' : '编辑'}优惠券`" />
        <el-form ref="ruleRef" :model="ruleForm" :rules="ruleCheck" label-width="140px">
            <el-form-item label="优惠券名称" prop="names">
                <el-input v-model.trim="ruleForm.names" clearable placeholder="请输入优惠券名称" />
            </el-form-item>
            <el-form-item label="面值" prop="price">
                <el-input
                    v-model.trim="ruleForm.price"
                    oninput="value=value.replace(/[^\d.]/g,'')"
                    clearable
                    placeholder="请输入面值，保留两位小数"
                />
                <span class="input-icon">元</span>
                <p class="input-tips">优惠券面额</p>
            </el-form-item>
            <!-- <el-form-item label="会员等级" prop="level_id">
                <el-select v-model="ruleForm.level_id" clearable placeholder="请选择会员等级">
                    <el-option :label="item.label" :value="item.level_id" v-for="item in level_arrs" :key="item.level_id" />
                </el-select>
            </el-form-item> -->
            <el-form-item label="订单金额" prop="order_price">
                <el-input
                    v-model.trim="ruleForm.order_price"
                    oninput="value=value.replace(/[^\d.]/g,'')"
                    clearable
                    placeholder="请输入订单金额，保留两位小数"
                />
                <span class="input-icon">元</span>
                <p class="input-tips">当订单金额<code>≥</code>订单金额时，才能使用优惠券</p>
            </el-form-item>
            <el-form-item label="领取方式" prop="radio_receive">
                <el-radio-group v-model="ruleForm.radio_receive">
                    <el-radio :label="0">不限</el-radio>
                    <el-radio :label="1">推送</el-radio>
                </el-radio-group>
                <p class="input-tips"><code>不限</code>表示前端有优惠券列表供用户领取，<code>推送</code>表示只能后台发放，前端无法主动领取</p>
            </el-form-item>
            <el-form-item label="发放总量" prop="nums">
                <el-input v-model.trim="ruleForm.nums" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入发放总量" />
                <span class="input-icon">张</span>
            </el-form-item>
            <el-form-item label="生效时间" prop="start_time">
                <el-date-picker
                    v-model="ruleForm.start_time"
                    type="datetime"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择生效时间"
                />
            </el-form-item>
            <el-form-item label="过期时间" prop="end_time">
                <el-date-picker
                    v-model="ruleForm.end_time"
                    type="datetime"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择过期时间"
                />
            </el-form-item>
            <el-form-item label="过期天数" prop="end_day">
                <el-input v-model.trim="ruleForm.end_day" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入过期天数" />
                <span class="input-icon">天</span>
            </el-form-item>
            <el-form-item label="使用说明" prop="remark">
                <el-input v-model.trim="ruleForm.remark" type="textarea" clearable :rows="4" placeholder="为了更好的用户体验，建议填写说明..." />
            </el-form-item>
            <el-form-item>
                <div style="margin-top: 20px">
                    <el-button type="primary" :loading="form_loading" @click="submitForm(ruleRef)"> 确认 </el-button>
                    <el-button @click="resetForm(ruleRef)">重置</el-button>
                </div>
            </el-form-item>
        </el-form>
    </div>
    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive } from "vue"
import { useRouter, useRoute } from "vue-router"
import GoBack from "@components/GoBack.vue"
import TitleMore from "@components/title-more.vue"

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

let type = route.query.type // 1是添加，2是编辑
let cid = route.query.cid || ""
onMounted(() => {
    cid && getDetail()
})

function getDetail() {
    proxy.$axios
        .get("coupon/update", {
            params: {
                coupon_id: cid,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                ruleForm.names = result.title
                ruleForm.price = result.coupon_amount
                ruleForm.order_price = result.order_amount
                ruleForm.nums = result.sku
                ruleForm.end_day = result.days_overdue
                ruleForm.remark = result.coupon_desc
                ruleForm.start_time = result.s_time_label
                ruleForm.end_time = result.l_time_label
                ruleForm.radio_receive = Number(result.type)
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

/**
 * 添加
 * @param {Boolean} form_loading 弹窗按钮状态
 * @property {Array} ruleRef 表单规则
 * @property {Object} ruleForm  表单字段
 * @property {Object} ruleCheck  表单提示
 */
const form_loading = ref(false)
const ruleRef = ref(null)
const ruleForm = reactive({
    names: "",
    price: "",
    radio_receive: 0,
    order_price: "",
    nums: "",
    start_time: "",
    end_time: "",
    end_day: "",
    remark: "",
    // level_id: "",
})
const ruleCheck = reactive({
    names: [{ required: true, message: "请输入优惠券名称", trigger: "blur" }],
    price: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    // level_id: [{ required: true, message: "请选择会员等级", trigger: "change" }],
    radio_receive: [{ required: true, message: "请选择领取方式", trigger: "change" }],
    order_price: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    nums: [{ required: true, message: "请输入优惠券发放总量", trigger: "blur" }],
    start_time: [{ required: true, message: "请选择生效时间", trigger: "change" }],
    end_time: [{ required: true, message: "请选择过期时间", trigger: "change" }],
    end_day: [{ required: true, message: "请输入过期天数", trigger: "blur" }],
})
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = {
                title: ruleForm.names,
                coupon_amount: ruleForm.price,
                type: ruleForm.radio_receive,
                order_amount: ruleForm.order_price,
                sku: ruleForm.nums,
                s_time: ruleForm.start_time,
                l_time: ruleForm.end_time,
                days_overdue: ruleForm.end_day,
                coupon_desc: ruleForm.remark,
                // level_id: ruleForm.level_id,
            }
            if (type == 2 && cid) {
                data.coupon_id = cid
            }
            let urls = type == 1 ? "coupon/add" : "coupon/update"
            proxy.$axios
                .post(urls, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        let texts = type == 1 ? "添加成功！" : "修改成功！"
                        proxy.$message({ message: texts, type: "success" })
                        router.push("/Marketing/CouponList")
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

// 会员等级
// const level_arrs = ref([
//     {
//         level_id: 1,
//         label: "一星会员",
//     },
//     {
//         level_id: 2,
//         label: "二星会员",
//     },
// ])
// function getLevel() {
//     proxy.$axios
//         .get("")
//         .then((res) => {
//             if (res.data.code == 0) {
//                 level_arrs.value = res.data.data
//             } else {
//                 proxy.$message({message:res.data.msg,type:"error"})
//             }
//         })
//         .catch((err) => {})
// }
</script>
<script>
export default {
    name: "CouponGiveUpdate",
}
</script>

<style lang="less" scoped>
.input-icon {
    margin-left: @margin-sm;
    color: @gray-7;
}
</style>
